from flask import Blueprint, request, jsonify, current_app
import time
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models.checkin_model import CheckinRecord, Question
from bson import ObjectId

checkin_bp = Blueprint('checkin', __name__, url_prefix='/api')

@checkin_bp.post('/checkin/submit')
@jwt_required()
def submit_checkin():
    """提交打卡记录"""
    try:
        # 从JWT中获取用户ID（优先使用JWT中的ID确保安全）
        jwt_user_id = get_jwt_identity()
        if not jwt_user_id:
            return jsonify({"code": -1, "msg": "未获取到用户信息，请重新登录"}), 401
            
        data = request.json
        
        # 验证核心参数
        required_fields = ['buildingName', 'buildingType']  # 调整必填字段
        for field in required_fields:
            if field not in data:
                return jsonify({"code": -1, "msg": f"缺少参数：{field}"}), 400
        
        # 构建记录数据（严格匹配数据表结构）
        record_data = {
            # 强制使用JWT中的用户ID，防止篡改
            'userId': jwt_user_id,
            'buildingId': data.get('buildingId', f"auto_{int(time.time())}"),  # 自动生成ID
            'buildingName': data['buildingName'],
            'sceneryName': data.get('sceneryName', ''),
            'checkinTime': time.strftime('%Y-%m-%dT%H:%M:%S.000+00:00', time.gmtime()),
            'images': data.get('images', []),
            'comment': data.get('comment', ''),
            'hasAnswered': False,
            'score': 0,
            'location': data.get('location', {}),
            'stampId': '',
            'stampUrl': '',
            'createdAt': time.strftime('%Y-%m-%dT%H:%M:%S.000+00:00', time.gmtime()),
            'updatedAt': time.strftime('%Y-%m-%dT%H:%M:%S.000+00:00', time.gmtime())
        }
        
        # 创建打卡记录
        record = CheckinRecord.create_record(record_data)
        if not record:
            return jsonify({"code": -1, "msg": "打卡记录创建失败"}), 500
        
        return jsonify({
            "code": 0,
            "msg": "打卡成功",
            "data": {
                "recordId": record['id'],
                "stampUrl": record['stampUrl']
            }
        })
        
    except Exception as e:
        current_app.logger.error(f"提交打卡失败: {str(e)}")
        return jsonify({"code": -1, "msg": f"提交失败：{str(e)}"}), 500

@checkin_bp.get('/checkin/history')
@jwt_required()
def get_checkin_history():
    """获取用户打卡历史记录"""
    try:
        user_id = get_jwt_identity()
        if not user_id:
            return jsonify({"code": -1, "msg": "未获取到用户信息，请重新登录"}), 401
        
        # 获取分页参数，默认第一页，每页10条
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        skip = (page - 1) * limit
        
        # 查询用户的打卡记录，按创建时间倒序
        records, total = CheckinRecord.get_user_records(
            user_id=user_id,
            skip=skip,
            limit=limit
        )
        
        # 格式化返回数据
        history_list = []
        for record in records:
            history_list.append({
                "recordId": record.get('id'),
                "buildingName": record.get('buildingName'),
                "sceneryName": record.get('sceneryName'),
                "checkinTime": record.get('checkinTime'),
                "images": record.get('images'),
                "comment": record.get('comment'),
                "score": record.get('score'),
                "stampUrl": record.get('stampUrl'),
                "hasAnswered": record.get('hasAnswered')
            })
        
        return jsonify({
            "code": 0,
            "msg": "获取成功",
            "data": {
                "list": history_list,
                "total": total,
                "page": page,
                "limit": limit
            }
        })
        
    except Exception as e:
        current_app.logger.error(f"获取打卡历史失败: {str(e)}")
        return jsonify({"code": -1, "msg": f"获取失败：{str(e)}"}), 500

@checkin_bp.get('/checkin/locations')
@jwt_required()
def get_checkin_locations():
    """获取用户打卡地点列表"""
    try:
        user_id = get_jwt_identity()
        if not user_id:
            return jsonify({"code": -1, "msg": "未获取到用户信息，请重新登录"}), 401
        
        # 获取用户所有打卡过的独特地点
        locations = CheckinRecord.get_unique_locations(user_id=user_id)
        
        # 格式化地点数据
        location_list = []
        for loc in locations:
            location_list.append({
                "buildingId": loc.get('buildingId'),
                "buildingName": loc.get('buildingName'),
                "sceneryName": loc.get('sceneryName'),
                "location": loc.get('location'),
                "lastCheckinTime": loc.get('checkinTime')
            })
        
        return jsonify({
            "code": 0,
            "msg": "获取成功",
            "data": {
                "locations": location_list
            }
        })
        
    except Exception as e:
        current_app.logger.error(f"获取打卡地点失败: {str(e)}")
        return jsonify({"code": -1, "msg": f"获取失败：{str(e)}"}), 500

@checkin_bp.get('/questions/building/<building_id>')
@jwt_required()
def get_questions_by_building(building_id):
    """根据建筑ID获取相关问题"""
    try:
        user_id = get_jwt_identity()
        if not user_id:
            return jsonify({"code": -1, "msg": "未获取到用户信息，请重新登录"}), 401
        
        # 查询该建筑对应的问题
        questions = Question.get_by_building_id(building_id=building_id)
        
        # 格式化问题数据
        question_list = []
        for q in questions:
            question_list.append({
                "questionId": q.get('id'),
                "questionContent": q.get('content'),
                "options": q.get('options'),
                "buildingId": q.get('buildingId'),
                "buildingType": q.get('buildingType')
            })
        
        return jsonify({
            "code": 0,
            "msg": "获取成功",
            "data": {
                "questions": question_list
            }
        })
        
    except Exception as e:
        current_app.logger.error(f"获取建筑问题失败: {str(e)}")
        return jsonify({"code": -1, "msg": f"获取失败：{str(e)}"}), 500

@checkin_bp.get('/questions/type/<building_type>')
@jwt_required()
def get_questions_by_type(building_type):
    """根据建筑类型获取相关问题"""
    try:
        user_id = get_jwt_identity()
        if not user_id:
            return jsonify({"code": -1, "msg": "未获取到用户信息，请重新登录"}), 401
        
        # 调用模型方法：根据建筑类型查询题目
        questions = Question.get_by_building_type(building_type=building_type)
        
        # 格式化返回数据（与前端checkin.ts逻辑匹配，直接返回数组）
        question_list = []
        for q in questions:
            question_list.append({
                "questionId": q.get('id'),
                "questionContent": q.get('content'),
                "options": q.get('options'),
                "buildingId": q.get('buildingId'),
                "buildingType": q.get('buildingType')
            })
        
        return jsonify({
            "code": 0,
            "msg": "获取成功",
            "data": question_list  # 直接返回问题数组，不嵌套在questions键中
        })
        
    except Exception as e:
        current_app.logger.error(f"获取建筑类型问题失败: {str(e)}")
        return jsonify({"code": -1, "msg": f"获取失败：{str(e)}"}), 500

@checkin_bp.post('/questions/verify')
@jwt_required()
def verify_answer():
    """验证问题答案并更新打卡记录"""
    try:
        user_id = get_jwt_identity()
        if not user_id:
            return jsonify({"code": -1, "msg": "未获取到用户信息，请重新登录"}), 401
        
        data = request.json
        required_fields = ['recordId', 'answers']
        for field in required_fields:
            if field not in data:
                return jsonify({"code": -1, "msg": f"缺少参数：{field}"}), 400
        
        record_id = data['recordId']
        answers = data['answers']  # 格式: [{questionId: "", answer: ""}, ...]
        
        # 验证答案正确性
        correct_count = 0
        total_count = len(answers)
        question_ids = [item['questionId'] for item in answers]
        
        # 获取所有问题的正确答案
        questions = Question.get_by_ids(question_ids=question_ids)
        question_map = {q['id']: q for q in questions}
        
        # 比对答案
        for item in answers:
            q_id = item['questionId']
            user_answer = item['answer']
            if q_id in question_map and question_map[q_id].get('correctAnswer') == user_answer:
                correct_count += 1
        
        # 计算得分
        score = int((correct_count / total_count) * 100) if total_count > 0 else 0
        
        # 更新打卡记录
        update_data = {
            'hasAnswered': True,
            'score': score,
            'updatedAt': time.strftime('%Y-%m-%dT%H:%M:%S.000+00:00', time.gmtime())
        }
        success = CheckinRecord.update_record(
            record_id=record_id,
            user_id=user_id,  # 验证记录归属权
            update_data=update_data
        )
        
        if not success:
            return jsonify({"code": -1, "msg": "更新打卡记录失败"}), 500
        
        return jsonify({
            "code": 0,
            "msg": "答案验证成功",
            "data": {
                "score": score,
                "correctCount": correct_count,
                "totalCount": total_count
            }
        })
        
    except Exception as e:
        current_app.logger.error(f"验证答案失败: {str(e)}")
        return jsonify({"code": -1, "msg": f"验证失败：{str(e)}"}), 500